package com.nave.segundaguerra.servidorecliente.util;

import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

import com.example.honraepodercliente.R;
import com.nave.segundaguerra.activity.ActivityListaIps;
import com.nave.segundaguerra.activity.ServerListComponent;
import com.nave.segundaguerra.servidorecliente.util.ControleDeUsuariosPortScan;
import com.nave.segundaguerra.servidorecliente.util.Protocolo;
import com.nave.segundaguerra.servidorecliente.util.RedeUtil;
import com.nave.segundaguerra.servidorecliente.util.ViewUtil;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Message;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.graphics.PorterDuff;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;

public class ProcuraServers extends AsyncTask<Void, Void, Void> {

	// List<String> Ips = new CopyOnWriteArrayList();
	private ArrayList<ServerListComponent> serversList;

	private ControleDeUsuariosPortScan PortScan;
	// String IpServerAberto = null;
	// private String ultimoIP =null;
	// private ListIps activityList;

	private ProgressDialog progressDialog;

	private static ProcuraServers instance;
	
	private ProcuraServers() {
		PortScan = new ControleDeUsuariosPortScan(this);
		serversList = new ArrayList<ServerListComponent>();

	}

	public static ProcuraServers getInstance() {
		if (instance == null) {
			instance = new ProcuraServers();
		}
		return instance;
	}

	private void procurar() {

		String MeuIP = RedeUtil.getLocalIpAddress();

		long numIps = calculoIps(MeuIP);
		Log.i("PortScan", "" + numIps);
		// String[] listIps = new String[(int) numIps];
		Log.i("PortScan", "Criou a lista");
		String[] parteIP = MeuIP.split("\\.");
		String baseIP = parteIP[0] + "." + parteIP[1] + "." + parteIP[2];
		// this.ultimoIP = baseIP +"."+ numIps;

		for (long i = 1; i < numIps; i++) {

			if (isCancelled()) {
				
				try {
					instance.finalize();
				} catch (Throwable e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				break;
			}else{
				Socket s;
				try {
					Log.i("PortScan", "procurando em :" + baseIP + "." + i
							+ " :  " + Protocolo.PORTA_RECONHECIMENTO);
					s = new Socket(baseIP + "." + i,
							Protocolo.PORTA_RECONHECIMENTO);
					Connection conect = new Connection(s, "PortScan", PortScan);
					conect.Send(Protocolo.CLIENT_REQUEST);

				} catch (UnknownHostException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

		}

	}

	private long calculoIps(String Ip) {

		// String[] PartesIp = Ip.split("\\.");
		int Octeto = Integer.parseInt(Ip.split("\\.")[0]);

		if (Octeto >= 1 && Octeto <= 126) {
			return 16777214;
		} else if (Octeto >= 128 && Octeto <= 191) {
			return 16384;
		} else if (Octeto >= 192 && Octeto <= 223) {
			return 254;
		}

		return 0;
	}

	/*
	 * // private List<String> outrosIps(int numIps){ // // List<String> Ips =
	 * new CopyOnWriteArrayList(); // // for (int i = 1; i < numIps; i++) { //
	 * Ips.add(""+i); // } // return Ips; // }
	 */

	public void encontrouIP(String IP, String nameServer, String numDeVagas) {

		Log.i("PortScan", "um ip foi encontrado" + IP);

		// activityList.setServers(nameServer, numDeVagas, IP);
		ServerListComponent server = new ServerListComponent(IP, nameServer, numDeVagas);

		serversList.add(server);

		ActivityUtil.ChangeActivity(ActivityListaIps.class);
		
		
	}

	public void ipInvalido(String IP) {

	}

	public ArrayList<ServerListComponent> getList() {
		return this.serversList;
	}
	
	public void cancelPesquisa(){
		cancel(true);
		try {
			this.finalize();
			instance = null;
		} catch (Throwable e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	protected void onPreExecute() {
		showLoad();
	}
	
	private void showLoad(){
		progressDialog = new ProgressDialog(ActivityUtil.getCurrentActivity());

		progressDialog.setMessage("Aguarde...");

		progressDialog.setButton("Cancelar", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {

				cancelPesquisa();
			}
		});
		progressDialog.show();
		
		
		
		

	}

	@Override
	protected Void doInBackground(Void... v) {

		procurar();

		return null;

	}

	@Override
	protected void onPostExecute(Void result) {

		progressDialog.dismiss();

	}

	@SuppressWarnings("unused")
	@Deprecated
	private Byte[] parseIPforBytes(String IP) {

		Byte[] IpByte = new Byte[32];

		String[] PartesDoIP = IP.split(".");

		if (PartesDoIP.length != 4) {
			return null;
		}

		for (int i = 0; i <= 3; i++) {

			int octeto = Integer.parseInt(PartesDoIP[i]);

			if (octeto >= 128) {
				IpByte[(1 + (8 * i)) - 1] = 1;
				octeto -= 128;
			} else {
				IpByte[(1 + (8 * i)) - 1] = 0;
			}

			if (octeto >= 64) {
				IpByte[(2 + (8 * i)) - 1] = 1;
				octeto -= 64;
			} else {
				IpByte[(2 + (8 * i)) - 1] = 0;
			}

			if (octeto >= 32) {
				IpByte[(3 + (8 * i)) - 1] = 1;
				octeto -= 32;
			} else {
				IpByte[(3 + (8 * i)) - 1] = 0;
			}

			if (octeto >= 16) {
				IpByte[(4 + (8 * i)) - 1] = 1;
				octeto -= 16;
			} else {
				IpByte[(4 + (8 * i)) - 1] = 0;
			}

			if (octeto >= 8) {
				IpByte[(5 + (8 * i)) - 1] = 1;
				octeto -= 8;
			} else {
				IpByte[(5 + (8 * i)) - 1] = 0;
			}

			if (octeto >= 4) {
				IpByte[(6 + (8 * i)) - 1] = 1;
				octeto -= 4;
			} else {
				IpByte[(6 + (8 * i)) - 1] = 0;
			}

			if (octeto >= 2) {
				IpByte[(7 + (8 * i)) - 1] = 1;
				octeto -= 2;
			} else {
				IpByte[(7 + (8 * i)) - 1] = 0;
			}

			if (octeto >= 1) {
				IpByte[(8 + (8 * i)) - 1] = 1;
				octeto -= 1;
			} else {
				IpByte[(8 + (8 * i)) - 1] = 0;
			}

		}

		return IpByte;

	}

}
